//
//  MHCircleSearchViewModel.m
//  MiaoCircle
//
//  Created by Xuzhengrong on 2018/8/17.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHCircleSearchViewModel.h"
#import "MLCircleInfoMainPageViewModel.h"
#import "MHSearchCircleModel.h"
#import "MHWebViewModel.h"
#import "MHSerchMoment.h"
#import "MHMomentDetailViewModel.h"
#import "MHCustomItemViewModel.h"

@implementation MHCircleSearchViewModel

-(void)initialize
{
    [super initialize];
    self.shouldPullDownToRefresh = NO;
    self.shouldPullUpToLoadMore = YES;
    self.shouldRequestRemoteDataOnViewDidLoad = false;
    self.shouldEndRefreshingWithNoMoreData = NO;
    self.shouldMultiSections = YES;
    
    RAC(self, datas) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    @weakify(self);
    RAC(self,dataSource) = [RACObserve(self, datas) map:^(NSArray * circles) {
        @strongify(self)
        return [self dataSourceWithCircles:circles];
    }];
    
    self.searchCircleCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        return [[[self.services.client searchCirclePagedListWithTitle:self.searchText pageNum:1 pageSize:4] mh_parsedResults] map:^(NSArray * circles) {
            if (MHObjectIsNil(circles) || circles.count == 0) return @[];
            NSArray *viewModels = [circles.rac_sequence map:^(id data) {
                MHCustomItemViewModel *viewModel = [[MHCustomItemViewModel alloc] initWithModel:data];
                return viewModel;
            }].array;
            return viewModels;
        }];
    }];
    
    
    self.didSelectCommand  = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        NSIndexPath *indexPath = input;
//         [[NSNotificationCenter defaultCenter] postNotificationName:SEARCH_CANCEL_NOTIFICATION_KEY object:nil];
        if(indexPath.section == 1)
        {
             MHSerchMoment *searchMoment =  self.datas[indexPath.row];
            if (searchMoment.vedioCount) {
                return   [[[self.services.client getRecentInfoByNewVideoWithRecentId:searchMoment.autoId] mh_parsedResults] doNext:^(MHAwemeModel *model) {
                    MHAwemeListViewModel *viewModel = [[MHAwemeListViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:@[model],@"MHViewModelShowEnterBtn":@false,@"MHViewModelShowSingleVideo":@true}];
                    [self.services pushViewModel:viewModel animated:YES];
                }];
                
            }else
            {
                MHMomentDetailViewModel *detail = [[MHMomentDetailViewModel alloc] initWithServices:self.services params:@{MHViewModelIDKey:@(searchMoment.autoId),MHViewModelIsDetail:@(true)}];
                [self.services pushViewModel:detail animated:YES];
                return [RACSignal empty];
            }
        }else
        {
           
            MHCustomItemViewModel *item = self.searchRecent[indexPath.row];
            MHSearchCircleModel *searchMoment = item.model;
            if (searchMoment.isInCircle) {
//                MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.services params:@{MHViewModelIDKey:@(searchMoment.circleId)}];
//                [self.services pushViewModel:viewModel animated:YES];
                 [MHMomentHelper redirectToGroupChatWithCircleId:searchMoment.circleId service:self.services groupId:searchMoment.circleCode title:searchMoment.title];
                return [RACSignal empty];
            }else
            {
                NSString *detailUrl =  [NSString stringWithFormat:@"%@join-circle-app.html?circleId=",[MHConfigureManager h5BaseUrl]];
                NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@%ld&userId=%d",detailUrl,(long)searchMoment.circleId,[MHHTTPService sharedInstance].currentUser.userId]];
                
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                MHWebViewModel * webViewModel = [[MHWebViewModel alloc] initWithServices:self.services params:@{MHViewModelRequestKey:request}];
                webViewModel.showBottomButton = false;
                [self.services pushViewModel:webViewModel animated:YES];
                return [RACSignal empty];
            }
        }
    }];
}




- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapCircles)(NSArray *) = ^(NSArray *products) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            products = @[(self.datas ?: @[]).rac_sequence, products.rac_sequence].rac_sequence.flatten.array;
        }
        return products;
    };
    return  [[[self.services.client searchRecentByContentPagedListWithText:self.searchText pageNum:page pageSize:self.perPage circleId:0] mh_parsedResults] map:mapCircles];
}


- (NSArray *)dataSourceWithCircles:(NSArray *)datas {
    if (MHObjectIsNil(datas) || datas.count == 0) return self.searchRecent ? @[self.searchRecent] : @[];
    NSArray *viewModels = [datas.rac_sequence map:^(id data) {
        MHCustomItemViewModel *viewModel = [[MHCustomItemViewModel alloc] initWithModel:data];
        return viewModel;
    }].array;
    return  @[self.searchRecent ?: @[] ,viewModels ?: @[] ];
}

//-(RACSignal *)customSignalWithPage:(NSInteger)page
//{
//    return  [self.services.client searchRecentByContentPagedListWithText:self.searchText pageNum:page pageSize:self.perPage circleId:0];
//}
@end
